<!-- 
未作：
1. 备注输入框，未绑定商品
2. 优惠券没有做选择，已经修改
3. 修改商品参数 -->

<template>
  <view class="wrapper">
    <!-- 地址选择 -->
    <view class="address-choose item">
      <view class="address">
        <view class="left">
          <image src="../../static/address.svg"></image>
        </view>
        <view class="middle">
          <view class="content">{{ formatAddress(address.province_city_district) + address.address_detail }}</view>
          <view class="contact">{{ address.consignee }} &nbsp;&nbsp; {{ address.phone_number }}</view>
        </view>
        <view class="right">
          <image src="../../static/downpush.png"></image>
        </view>
      </view>
    </view>

    <!-- 商品展示 -->
    <!-- 配送费用 -->
    <!-- 订单备注 -->

    <view class="item">
      <view class="goods-item" v-for="orderItem in itemList" :key="orderItem.id">
        <view class="goods-item-top">
          <view class="goods-left">
            <image :src="orderItem.goods_info.cover_url"></image>
          </view>

          <view class="goods-middle">
            <view class="goods-title">{{ orderItem.goods_info.name }}</view>
            <view class="goods-type">商品参数：{{ checkWordsLength(orderItem.goods_param.name, 32) }}</view>
          </view>

          <view class="goods-price">
            <view class="goods-curl-price" v-if="computedRealCoupontPrice(orderItem) != 0">
              券后
              <text>￥{{ computedRealCoupontPrice(orderItem) }}</text>
            </view>
            <view class="goods-set-price">￥{{ toFixedPrice(orderItem.price, 2) }}</view>
          </view>
        </view>
        <view class="goods-item-middle">
          <view class="goods-count">数量：{{ orderItem.count }}</view>
        </view>

        <view class="goods-item-bottom">
          <view>配送服务</view>

          <view>
            <span v-if="orderItem.goods_info.logistics_price == null || orderItem.goods_info.logistics_price == 0">
              包邮
            </span>
            <span v-else>￥{{ orderItem.goods_info.logistics_price }}</span>
            <view class="right">
              <image></image>
            </view>
          </view>

          <view>商品惠券</view>

          <view @click="handleChooseCoupon()">
            {{ findCouponName(orderItem.goods_id) }}
            <view class="right">
              <image src="../../static/downpush.png"></image>
            </view>
          </view>

          <view>订单备注</view>

          <view @click="showTextarea = true">
            <text
              class="no-remarks"
              v-if="orderItem.remark == null || orderItem.remark == '' || orderItem.remark.length === 0"
            >
              无备注
            </text>
            <view class="remarks" v-else>{{ checkWordsLength(orderItem.remark, 12) }}</view>
            <view class="right">
              <image src="../../static/downpush.png"></image>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 价格明细（当前商品优惠、优惠券），合计 -->

    <view class="item price-detail">
      <view class="title">价格明细</view>

      <view class="price-item">
        <view class="title">商品总价</view>
        <view class="price">
          <span class="small-price">￥</span>
          {{ formatPrice(order.total_price).big }}.
          <span class="small-price">{{ formatPrice(order.total_price).small }}</span>
        </view>
        <view class="right"></view>
      </view>
      <view class="price-item">
        <view class="title">快递费用</view>
        <view class="price">
          <template v-if="order.total_logistics != 0">
            <span class="small-price">￥</span>
            {{ formatPrice(order.total_logistics).big }}.
            <span class="small-price">{{ formatPrice(order.total_logistics).small }}</span>
          </template>
          <span v-else>包邮</span>
        </view>
        <view class="right"></view>
      </view>

      <view class="price-item" v-if="order.total_price > order.real_price">
        <view class="title">共减</view>
        <view class="red-price">
          -
          <span class="small-price">￥</span>
          {{ formatPrice(totalSubPrice).big }}.
          <span class="small-price">
            {{ formatPrice(totalSubPrice).small }}
          </span>
        </view>
        <view class="right"></view>
      </view>

      <view
        class="price-item"
        @click="handleChooseCoupon()"
        v-for="coupon in couponList"
        :key="coupon.discountObj.user_coupon_id"
      >
        <view class="small-title">
          <image src="../../static/gold.svg"></image>
          {{ coupon.name }}
        </view>
        <view class="red-price" v-if="coupon.discountObj.category === 12 || coupon.discountObj.category === 11">
          -
          <span class="small-price">￥</span>
          {{ formatPrice(coupon.discountObj.discount_price).big }}.
          <span class="small-price">{{ formatPrice(coupon.discountObj.discount_price).small }}</span>
        </view>

        <view v-else>
          <span v-if="coupon.allGoods">全平台</span>
          <span v-else>指定商品</span>
          包邮
        </view>

        <view class="right">
          <image src="../../static/downpush.png"></image>
        </view>
      </view>

      <view class="price-item">
        <view class="title">合计</view>
        <view class="price">
          <span class="small-price">￥</span>
          {{ formatPrice(order.real_price).big }}.
          <span class="small-price">{{ formatPrice(order.real_price).small }}</span>
        </view>
        <view class="right"></view>
      </view>
    </view>

    <!-- 底部浮空（共计1件，合计：多少钱，共减多少钱，提交订单按钮（点击跳转支付）） -->

    <view class="fixed-bottom">
      <view class="fixed-content">
        <view class="left">
          <view class="top">
            <text class="total-count">共{{ itemList.length }}件</text>
            <text class="total-price">
              合计：

              <text class="small-price">￥</text>

              <text class="price">{{ formatPrice(order.real_price).big }}.</text>
              <text class="small-price">{{ formatPrice(order.real_price).small }}</text>
            </text>
          </view>

          <view class="bottom" v-if="order.total_price > order.real_price">
            共减&nbsp;&nbsp;￥
            {{ totalSubPrice }}
          </view>
        </view>
        <view class="right">
          <view class="pay-btn" @click="handlePay(order.id)">支付</view>
        </view>
      </view>
    </view>

    <!-- 备注输入框 -->
    <view class="remarks-wrapper-fixed" :style="{ top: showTextarea ? '0%' : '100%' }">
      <view class="mask" @click="handleCloseTextarea()"></view>

      <view class="remarks-wrapper">
        <textarea placeholder-style="color:#a1a1a1" placeholder="请输入备注" v-model="remarks" />
        <view class="remark-count">{{ remarks.length }} / {{ textareaCountMax }}</view>
        <view class="remarks-update-wrapper">
          <view class="remarks-update-btn" @click="handleUpdateRemarks()">修改</view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import formatAddress from '../../utils/formatAddress'
import { formatPrice, calculateAddPrice, calculateSubPrice } from '../../utils/formatPrice'

export default {
  data() {
    return {
      // goodstype: '净重 10 kg净重 10 kg净重 10 kg净重 10 kg净重 10 kg净重 10 kg净重 10 kg净重 10 kg净重 10 kg',
      remarks: '',
      order: {
        real_price: '0.00',
        total_logistics: '0.00'
      },
      itemList: [],
      realPrice: '',
      totalLogisticsPrice: '',
      totalPrice: '',
      usedCouponMap: [],
      couponList: [],

      showTextarea: false,
      textareaCountMax: 140,
      address: {
        id: '',
        address_detail: '',
        consignee: '',
        is_default: '',
        phone_number: '',
        province_city_district: '',
        user_id: ''
      },
      formatAddress,
      formatPrice,
      calculateAddPrice,
      calculateSubPrice
    }
  },
  onLoad() {
    uni.showLoading({
      title: '数据加载中...',
      mask: true
    })
    this.user_id = parseInt(getApp().globalData.userInfo.id)
    if (getApp().globalData.orderInfo != null) {
      const orderInfo = getApp().globalData.orderInfo
      this.address = orderInfo.address
      this.order = orderInfo.order
      this.itemList = orderInfo.orderList
      this.realPrice = orderInfo.realPrice
      this.totalLogisticsPrice = orderInfo.totalLogisticsPrice
      this.totalPrice = orderInfo.totalPrice
      this.usedCouponMap = orderInfo.usedCouponMap
    }

    // 清空
    getApp().globalData.orderInfo = null

    setTimeout(() => {
      uni.hideLoading()
    }, 500)
  },

  watch: {
    usedCouponMap(n) {
      // 获取coupon信息，整理到couponList
      for (const key in n) {
        if (Object.prototype.hasOwnProperty.call(n, key)) {
          const element = n[key]
          if (element.discountObj.user_coupon_id != 0) {
            this.couponList.push(element)
          }
        }
      }
    }
  },
  computed: {
    totalSubPrice() {
      const price = calculateSubPrice(
        this.order.total_price,
        calculateSubPrice(this.order.real_price, this.order.total_logistics)
      ).toFixed(2)
      if (price) return price
      return '0.00'
    }
  },

  methods: {
    getData() {},

    async getCouponInfo(id) {
      const { data: res } = await uni.request({
        url: this.$domain.data + '/getCouponInfoByUserCouponId/' + id,
        header: getApp().globalData.header
      })

      // console.log(res)
    },
    checkWordsLength(words, count) {
      if (words.length > count) {
        words = words.slice(0, count) + '...'
      }
      return words
    },

    computedRealCoupontPrice(item) {
      return calculateSubPrice(item.price, item.discount).toFixed(2)
    },

    findCouponName(goodsId) {
      try {
        const name = this.usedCouponMap[goodsId].name
        return name
      } catch {
        return '无可用优惠券'
      }
    },

    toFixedPrice(price, count) {
      return parseFloat(price).toFixed(count)
    },

    handleChooseCoupon() {
      // console.log('dianji')
      let goodsIdList = []

      this.itemList.forEach((element) => {
        goodsIdList.push(element.goods_id)
      })

      uni.navigateTo({
        url: `/pages/pay/chooseCoupon?orderId=${this.order.id}&goodsIdList=${JSON.stringify(goodsIdList)}`
      })
    },
    handleUpdateRemarks() {
      this.showTextarea = false
    },
    handleCloseTextarea() {
      this.showTextarea = false
      this.remarks = ''
    },
    handlePay(id) {
      uni.showModal({
        title: '提示',
        content: '模拟支付',
        success: async (e) => {
          if (e.confirm) {
            const { data: res } = await uni.request({
              url: this.$domain.data + '/pay/' + id,
              header: getApp().globalData.header,
              method: 'POST'
            })

            if (res.status != 200) {
              this.$checkStatus(res.status, '支付失败')
              return
            }

            setTimeout(() => {
              uni.showToast({
                icon: 'success',
                title: '支付成功'
              })
            }, 500)

            setTimeout(() => {
              // console.log(res)
              getApp().globalData.payId = res.data.pay_id

              uni.redirectTo({
                url: '/pages/pay/paysuccess'
              })
            }, 1000)
          } else {
            uni.showToast({
              icon: 'error',
              title: '取消支付'
            })

            setTimeout(() => {
              uni.redirectTo({
                url: '/pages/order/index?tab=0'
              })
            }, 1000)
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.wrapper {
  background-color: $uni-bg-color-grey;
  padding: 30upx 20upx;
  min-height: 100vh;
  box-sizing: border-box;

  font-size: 33upx;
}

.item {
  width: 100%;
  padding: 25upx;
  box-sizing: border-box;
  border-radius: 20upx;
  background-color: #fff;
  // min-height: 300upx;
  margin-bottom: 20upx;
}

.address-choose {
  .address {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .left {
      flex: 1;
      image {
        width: 50upx;
        height: 50upx;
      }
    }

    .middle {
      padding-left: 20upx;
      box-sizing: border-box;
      flex: 10;
      .content {
        font-size: 32upx;
      }

      .contact {
        margin-top: 5upx;
        font-size: 27upx;
      }
    }

    .right {
      flex: 2;
      // background-color: aqua;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      image {
        transform: rotate(-90deg);
        width: 30upx;
        height: 30upx;
      }
    }
  }
}

.goods-item:last-child {
  margin-bottom: 0upx;
  border: none;
}

.goods-item {
  width: 100%;
  height: 100%;
  margin-bottom: 60upx;
  padding-bottom: 40upx;
  border-bottom: 2upx solid rgba($color: #000000, $alpha: 0.05);
  .goods-item-top {
    display: flex;
    justify-content: flex-start;
    align-items: flex-start;

    .goods-left {
      flex: 2;
      image {
        width: 150upx;
        height: 150upx;
        border-radius: 20upx;
        flex: 1;
      }
    }

    .goods-middle {
      // background-color: aquamarine;
      font-size: 32upx;
      padding-left: 20upx;
      padding-right: 10upx;
      flex: 5;

      .goods-title {
        margin-bottom: 10upx;
      }

      .goods-type {
        font-size: 27upx;
        color: #a9a9a9;
        max-height: 90upx;
        overflow: hidden;
      }
    }

    .goods-price {
      flex: 2;
      font-size: 27upx;
      text-align: right;
      .goods-curl-price {
        color: $def-price-color;
        text {
          font-size: 30upx;
          font-weight: 900;
        }
      }

      .goods-set-price {
        color: #a8a8a8;
        font-weight: 900;
      }

      // background-color: blueviolet;
    }
  }

  .goods-item-middle {
    margin: 10upx 0;
    width: 100%;
    // background-color: #a9a9a9;
    display: flex;
    justify-content: flex-end;
    .goods-count {
      right: 80upx;
      display: flex;
      justify-content: center;
      align-items: center;
      top: 20upx;

      width: 230upx;
      height: 60upx;
      border: 3upx solid rgba($color: #000000, $alpha: 0.06);
      border-radius: 10upx;

      .count-add,
      .count-sub {
        flex: 1;

        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        cursor: pointer;
        font-weight: 900;
      }

      .count-add {
        border-radius: 0 10upx 10upx 0;
        border-left: 3upx solid rgba($color: #000000, $alpha: 0.06);
      }

      .count-sub {
        border-radius: 10upx 0 0 10upx;
        border-right: 3upx solid rgba($color: #000000, $alpha: 0.06);
      }

      .count-input {
        flex: 2;
        text-align: center;
      }
    }
  }

  .goods-item-bottom {
    margin-top: 30upx;
    display: grid;
    grid-template-columns: 1fr 4fr;
    row-gap: 30upx;
    font-size: 32upx;
    view {
      display: flex;
      justify-content: flex-end;
      align-items: center;
    }

    .no-remarks {
      color: #a9a9a9;
    }

    .right {
      // background-color: aqua;
      margin-left: 10upx;
      height: 100%;
      display: flex;
      justify-content: flex-end;
      image {
        transform: rotate(-90deg);
        width: 30upx;
        height: 30upx;
      }
    }
  }
}

.price-detail {
  .title {
    font-size: 35upx;
    font-weight: 900;
    flex: 5;
  }

  .price-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20upx;
    padding: 10upx 0;

    .small-title {
      flex: 4;
      font-size: 33upx;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      image {
        width: 50upx;
        height: 50upx;
      }
    }

    .red-price,
    .price {
      font-weight: 900;
      font-size: $def-price;
      text-align: right;

      .small-price {
        font-size: 25upx;
      }
    }

    .red-price {
      // flex: 2;
      // background-color: aqua;
      color: $def-price-color;
    }

    .right {
      // background-color: aqua;
      height: 100%;
      flex: 0.36;
      align-items: center;
      display: flex;
      justify-content: flex-end;
      image {
        transform: rotate(-90deg);
        width: 30upx;
        height: 30upx;
      }
    }
  }
}

.fixed-bottom {
  width: 100%;
  height: 130upx;
  position: relative;

  .fixed-content {
    width: 100%;
    height: 130upx;
    border-top: 1upx solid #ebe9e9;
    background-color: #fff;
    position: fixed;
    display: flex;
    justify-content: flex-end;
    align-items: center;

    padding-bottom: 80upx;
    // #ifndef H5
    bottom: -75upx;
    // #endif

    // #ifdef H5
    bottom: 49px;
    //#endif
    left: 0%;

    .left {
      margin-right: 20upx;
      display: flex;
      justify-content: center;
      align-items: flex-end;
      flex-direction: column;

      .top {
        .total-count {
          margin-right: 10upx;
          color: #a1a1a1;
        }

        .total-price {
          .small-price,
          .price {
            color: $def-price-color;
            font-weight: 900;
          }

          .small-price {
            font-size: 30upx;
          }
          .price {
            font-size: 40upx;
          }
        }
      }

      .bottom {
        font-size: 30upx;
        color: $def-price-color;
      }
    }

    .right {
      margin-right: 25upx;
      height: 100%;
      display: flex;
      justify-content: center;
      align-items: center;
      .pay-btn {
        width: 200upx;
        height: 80upx;
        border-radius: 40upx;
        font-weight: 900;
        display: flex;
        justify-content: center;
        align-items: center;
        letter-spacing: 10upx;
        color: #fff;
        background: $def-submit-bg;
      }
    }
  }
}

.remarks-wrapper-fixed {
  position: fixed;

  left: 0%;
  width: 100%;
  height: 100%;
  transition: 0.5s ease-in-out;

  .mask {
    width: 100%;
    height: 100%;
  }
  // background-color: #a1a1a1;
}

.remarks-wrapper {
  position: absolute;
  border-top: 1upx solid #ebe9e9;
  bottom: 0%;
  left: 0%;
  height: 350upx;
  width: 100%;
  background-color: #fff;
  padding: 30upx;
  box-sizing: border-box;

  .remark-count {
    font-size: 28upx;
    position: absolute;
    margin-top: 10upx;
    color: #a1a1a1;
  }

  .remarks-update-wrapper {
    display: flex;
    justify-content: flex-end;
    margin-top: 25upx;
    .remarks-update-btn {
      // margin: ;
      padding: 15upx 50upx;
      border-radius: 10upx;
      color: #fff;
      letter-spacing: 10upx;
      font-weight: 900;
      background-color: #ff5722;
    }
  }

  textarea {
    // background-color: aqua;
    width: 100%;
    height: 200upx;
    padding: 10upx;
    box-sizing: border-box;
    border: 2upx solid rgba($color: #000000, $alpha: 0.1);
    border-radius: 20upx;
  }
}
</style>
